package com.example.majiang.controller;


import com.example.majiang.dto.AccessTokenDTO;
import com.example.majiang.dto.GiteeUser;
import com.example.majiang.mapper.UserMappper;
import com.example.majiang.model.User;
import com.example.majiang.provider.GiteeProvider;
import com.example.majiang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class AuthorizeController {

    @Autowired
    GiteeProvider giteeProvider;

    @Value("${gitee.client.id}")
    private String clientId;
    @Value("${gitee.client.secret}")
    private String clientSecret;
    @Value("${gitee.client.redirect}")
    private String clientRedirect;
    @Autowired
    UserService userService;

    @GetMapping("/callback")
    public String callback(@RequestParam(name="code")String code, HttpServletRequest request, HttpServletResponse response){
        AccessTokenDTO accessTokenDTO=new AccessTokenDTO();
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(clientRedirect);
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setClient_secret(clientSecret);
        String token=giteeProvider.getAccessToken(accessTokenDTO);
        GiteeUser giteeUser=null;
        if(token!=null){
            System.out.println(token);
           giteeUser= giteeProvider.getUser(token);
            request.getSession().setAttribute("user",giteeUser);
        }
        if(giteeUser!=null){
            token=UUID.randomUUID().toString();
            User user=new User();
            user.setToken(token);
            user.setName(giteeUser.getName());
            user.setAccountId(String.valueOf(giteeUser.getId()));
            user.setAvatarUrl(giteeUser.getAvatarUrl());
            userService.createOrUpdate(user);
            response.addCookie(new Cookie("token",token));
            return "redirect:/";
        }
        else{
            return "redirect:/";
        }

    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request,HttpServletResponse response){
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
